<?php

namespace app\admin\controller;



class News extends Base
{
    public function index()
    {
        $whereData = [];
        $data = input('param.');
        // 转换查询条件
        if (!empty($data['start_time']) && !empty($data['end_time']) && $data['end_time'] > $data['start_time']) {
            $whereData['create_time'] = [
                ['gt', strtotime($data['start_time'])],
                ['lt', strtotime($data['end_time'])],
            ];
        }
        if (!empty($data['catid'])) {
            $whereData['catid'] = intval($data['catid']);
        }
        if (!empty($data['title'])) {
            $whereData['title'] = ['like', '%' . $data['title'] . '%'];
        }
        $news = model('News')->getNews($whereData);
        return $this->fetch('', [
            'cats'       => config('cat.lists'),
            'news'       => $news,
            'catid'      => !empty($data['catid']) ? $data['catid'] : '',
            'title'      => !empty($data['title']) ? $data['title'] : '',
            'start_time' => empty($data['start_time']) ? '' : $data['start_time'],
            'end_time'   => empty($data['end_time']) ? '' : $data['end_time'],
        ]);
    }

    public function add()
    {
        if (request()->isPost()) {
            $data = input('post.');
            //validate 数据校验
            $data['create_time'] = time();
            //数据入库
            try {
                $id =  model('News')->add($data);
            } catch (\Exception $e) {
                return $this->result('', 0, '新增失败');
            }
            if ($id) {
                return $this->result(['jump_url' => url('news/index')], 1, 'OK');
            } else {
                return $this->result('', 0, '新增失败');
            }
        } else {
            return $this->fetch('', [
                'cats' => config('cat.lists')
            ]);
        }
    }
}
